package cn.maihe.elg.operation.centers.hymake.handler.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.maihe.elg.operation.centers.hymake.config.HyMakeInfoConfig;
import cn.maihe.elg.operation.centers.hymake.dto.HyMakeBaseRespDTO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.LstApplyReqDTO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.LstApplyRespDTO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.TbInsuranceSchema;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.TbMainLiab;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.TbPolicyDto;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.TbProvinceSupply;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.TbSection;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.xm.XMBaseRespDTO;
import cn.maihe.elg.operation.centers.hymake.dto.handler.vo.xm.XMTenderer;
import cn.maihe.elg.operation.centers.hymake.enums.HyMakeRespCodeEnum;
import cn.maihe.elg.operation.centers.hymake.enums.XMRespCodeEnum;
import cn.maihe.elg.operation.centers.hymake.exception.HyMakeException;
import cn.maihe.elg.operation.centers.hymake.handler.HyMakeCenterTradeService;
import cn.maihe.elg.operation.centers.supports.CenterInterfaceService;
import cn.maihe.elg.operation.centers.supports.CenterInterfaceServiceFactory;
import cn.maihe.elg.operation.centers.supports.CenterTradeContext;
import cn.maihe.elg.operation.centers.supports.annotation.CenterTradeService;
import cn.maihe.elg.operation.model.bo.AcceptOrderBO;
import cn.maihe.elg.operation.model.bo.ApplyTemplatePdfParams;
import cn.maihe.elg.operation.model.dto.InnerBaseResp;
import cn.maihe.elg.operation.model.enums.AcceptOrderStatus;
import cn.maihe.elg.operation.model.enums.AttachmentFileType;
import cn.maihe.elg.operation.model.enums.BidCustomerStatus;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.CenterProviderEnum;
import cn.maihe.elg.operation.model.enums.CertifyCodeEnum;
import cn.maihe.elg.operation.model.enums.GuaranteeCategory;
import cn.maihe.elg.operation.model.enums.GuaranteeType;
import cn.maihe.elg.operation.model.enums.IDType;
import cn.maihe.elg.operation.model.enums.InnerRespCode;
import cn.maihe.elg.operation.model.enums.InstitutionOrgCodeEnum;
import cn.maihe.elg.operation.model.enums.InvoiceLineEnum;
import cn.maihe.elg.operation.model.enums.InvoiceStatusEnum;
import cn.maihe.elg.operation.model.enums.TradeType;
import cn.maihe.elg.operation.model.enums.UserStatusEnum;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDOCondition;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeInstitutionDO;
import cn.maihe.elg.operation.repository.entity.InvoiceInfoDO;
import cn.maihe.elg.operation.repository.entity.InvoiceInfoVo;
import cn.maihe.elg.operation.repository.entity.ProjectInfoDO;
import cn.maihe.elg.operation.repository.entity.UserDO;
import cn.maihe.elg.operation.repository.entity.UserDOCondition;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.ProjectInfoService;
import cn.maihe.elg.operation.service.invoice.InvoiceInfoService;
import cn.maihe.elg.operation.service.order.AcceptContentService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.service.order.NoticeRetryInfoService;
import cn.maihe.elg.operation.service.system.impl.UserServiceImpl;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.AutoDiscernTemplateUtil;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.StringUtil;
import cn.maihe.framework.starter.mybatis.mapper.PlusEntityWrapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Triple;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @Description 4.1.1承保接口
 * 接口功能描述
 * 电子保函平台向出函机构（保险公司/银行）推送承保信息，
 * 保函保费由出函机构计算后返回。
 * @Author WJH
 * @Date 2022/03/31
 */
@CenterTradeService(
        provider = CenterProviderEnum.XIANMEN,
        centerNo = CenterNoEnum.XIAMEN,
        tradeType = TradeType.lstApply,
        reqClass = LstApplyReqDTO.class,
        respClass = XMBaseRespDTO.class
)
@Slf4j
public class XMLstApplyService extends HyMakeCenterTradeService<LstApplyReqDTO, XMBaseRespDTO> {
    public XMLstApplyService(HyMakeInfoConfig centerInfosConfig, GuaranteeAttachmentInfoService guaranteeAttachmentInfoService) {
        super(centerInfosConfig);
        this.guaranteeAttachmentInfoService = guaranteeAttachmentInfoService;
    }

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private ElgResourceService elgResourceService;
    @Resource
    private GuaranteeAttachmentInfoService guaranteeAttachmentInfoService;
    @Resource
    private ProjectInfoService projectInfoService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private UserServiceImpl userServiceImpl;
    @Resource
    private AcceptContentService acceptContentService;
    @Resource
    private InvoiceInfoService invoiceInfoService;

    @Resource
    private HyMakeInfoConfig hyMakeInfoConfig;

    @Resource
    private NoticeRetryInfoService noticeRetryInfoService;

    @Override
    protected void verifyParam(CenterTradeContext<LstApplyReqDTO, XMBaseRespDTO> context) {
        super.verifyParam(context);

        LstApplyReqDTO req = context.getReq();

        TbPolicyDto policyDto = req.getTbPolicyDtoList().get(0);
        String centerOrderId = policyDto.getBusinessNo();
        long centerId = context.getCenterId();
        boolean exists = acceptOrderInfoService.existsCenterOrderId(centerId, centerOrderId);
        if(exists){
            return;
        }

        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
        String bidderCreditCode = insuranceSchema.getHolderIdNo();
        BidCustomerDO bidCustomerDO = bidCustomerService.getByCreditCode(bidderCreditCode, null);
        if(Objects.isNull(bidCustomerDO)){
            return;
        }

        long orgId = context.getOrgId();
        String sectionCode = provinceSupply.getSectionCode();
        String sectionName = provinceSupply.getSectionName();
        ProjectInfoDO projectInfo = projectInfoService.getBySectionCode(sectionCode,sectionName, centerId, orgId);
        if(Objects.isNull(projectInfo)) {
           return;
        }

        PlusEntityWrapper<AcceptOrderInfoDO> build = AcceptOrderInfoDOCondition.builder().andProjectIdEq(projectInfo.getId()).andBidCustomerIdEq(bidCustomerDO.getId()).build();
        List<AcceptOrderInfoDO> acceptOrderInfoDO = acceptOrderInfoService.selectList(build);
        if(CollectionUtils.isNotEmpty(acceptOrderInfoDO)) {
            for (AcceptOrderInfoDO acceptOrderInfo : acceptOrderInfoDO) {
                if(AcceptOrderStatus.CANCEL.getStatus() == acceptOrderInfo.getStatus() || AcceptOrderStatus.REVOKE_SUCCESS.getStatus() == acceptOrderInfo.getStatus()){
                    continue;
                }

                throw HyMakeException.of(HyMakeRespCodeEnum.FAILURE, "您已发起了该标段的投保申请，请勿重复申请！");
            }

        }
    }

    @Override
    public XMBaseRespDTO processService(CenterTradeContext<LstApplyReqDTO, XMBaseRespDTO> context) {
        LstApplyReqDTO req = context.getReq();
        TbPolicyDto policyDto = req.getTbPolicyDtoList().get(0);
        String centerOrderId = policyDto.getBusinessNo();
        long centerId = context.getCenterId();
        boolean exists = acceptOrderInfoService.existsCenterOrderId(centerId, centerOrderId);
        if (exists) {
//            AcceptOrderInfoDO curOrderInfo = acceptOrderInfoService.selectOne(AcceptOrderInfoDOCondition.builder()
//                    .andCenterIdEq(centerId).andCenterOrderIdEq(centerOrderId).build());
            AcceptOrderBO acceptOrderBO = this.parseApplyGuaranteeInfo(context);

            XMBaseRespDTO resp = new XMBaseRespDTO();
            try {
                bidCustomerService.checkBidderContractInfo(acceptOrderBO.getBidCustomer());
            } catch (Exception e) {
                resp.setErrorCode(HyMakeRespCodeEnum.FAILURE.getRespCode());
                resp.setErrorDesc(e.getMessage());
                return resp;
            }

//            acceptOrderBO.getAcceptOrderInfo().setAcceptOrderNo(curOrderInfo.getAcceptOrderNo());
            return updateLstApply(acceptOrderBO);
//            return XMBaseRespDTO.builder()
//                    .success(false)
//                    .errorCode(HyMakeCheckResultEnum.FAILURE.getCheckResult())
//                    .errorDesc("保单流水号已存在")
//                    .build();
        }

        AcceptOrderBO acceptOrderBO = this.parseApplyGuaranteeInfo(context);

        XMBaseRespDTO resp = new XMBaseRespDTO();
        try {
            bidCustomerService.checkBidderContractInfo(acceptOrderBO.getBidCustomer());
        } catch (Exception e) {
            resp.setErrorCode(HyMakeRespCodeEnum.FAILURE.getRespCode());
            resp.setErrorDesc(e.getMessage());
            return resp;
        }

        acceptOrderBO = acceptOrderInfoService.saveAcceptOrderBO(acceptOrderBO);

        resp = buildResp(acceptOrderBO);

        acceptContentService.saveOrUpdateAcceptContent(acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo(), context.getReq());

        AcceptOrderBO finalAcceptOrderBO = acceptOrderBO;

        makeAndSaveApplyFile(finalAcceptOrderBO);

        // 厦门接口返回的数据结构不一致，清楚多余数据
        resp.setSuccess(true);
        resp.clearParam();
        return resp;
    }

    private XMBaseRespDTO buildResp(AcceptOrderBO acceptOrderBO) {
        XMBaseRespDTO resp = HyMakeBaseRespDTO.success("承保完成", XMBaseRespDTO.class);
        //投标企业是否已提交企业认证资料且已审核通过
        BidCustomerDO bidCustomerDO = acceptOrderBO.getBidCustomer();

        LstApplyRespDTO.BizData data = new LstApplyRespDTO.BizData();
        AcceptOrderInfoDO acceptOrderInfo = acceptOrderBO.getAcceptOrderInfo();
        // 承保接口同步返回信息，等待中心投保材料地址推送后，中心获取支付链接时得兴才有介入审核
        data.setInsuranceNo(acceptOrderInfo.getGuaranteeNo());
        data.setPremium(StringUtil.toYuan(acceptOrderInfo.getGuaranteeFee()));
        //费率单位
        data.setRate(StringUtil.multiplyTen(acceptOrderInfo.getFeeRate(), 2));
        //跳转到该订单上传申请书&反担保协议书 及 支付凭证页面
//        makeAndSaveApplyFile(acceptOrderBO);
        resp.setData(data);
        return resp;
    }

    /**
     * docx模板合成申请书
     */
    private void makeAndSaveApplyFile(AcceptOrderBO acceptOrderBO) {
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                log.error("3.1.3、、推送电子保函申请单 延时失败"+e.getMessage(),e);
            }

            ApplyTemplatePdfParams params = new ApplyTemplatePdfParams();
            params.setBidderName(acceptOrderBO.getBidCustomer().getBidderName());
            params.setProjectName(acceptOrderBO.getProjectInfo().getProjectName());
            Triple<String, String, String> triple = DateUtil.parseLocalDate();
            params.setYear(triple.getLeft());
            params.setMonth(triple.getMiddle());
            params.setDay(triple.getRight());
            AcceptOrderInfoDO orderInfo = acceptOrderBO.getAcceptOrderInfo();
            String acceptOrderNo = orderInfo.getAcceptOrderNo();
            Path docxPath = elgResourceService.buildApplyFileByTemplate(acceptOrderNo, params);

            System.out.println("");

            System.out.println(elgResourceService.getFileName(docxPath));
            System.out.println(elgResourceService.getFileType(docxPath));
            System.out.println(elgResourceService.getRelativePath(docxPath));
            System.out.println(elgResourceService.getFileMD5AsHex(docxPath));

            guaranteeAttachmentInfoService.saveOrUpdateAttachmentInfo(orderInfo, docxPath, AttachmentFileType.TYPE_12, "申请书未签章");


            CenterInterfaceService centerInterfaceService = CenterInterfaceServiceFactory.getByCenterNoEnum(centerNoEnum);
            InnerBaseResp<String> stringInnerBaseResp = centerInterfaceService.pushGuarantee(docxPath, acceptOrderNo);

            //todo:alan 开发环境暂不推送保函申请单到中心
            if (!InnerRespCode.SUCCESS.getRespCode().equals(stringInnerBaseResp.getRespCode().getRespCode())) {
                log.error("3.1.3、推送电子保函申请单失败 >> [{}] 异常:{}", CenterNoEnum.XIAMEN.getCenterName(), stringInnerBaseResp.getMessage());
                throw new RuntimeException("3.1.3、推送电子保函申请单失败");
            }
        }).whenCompleteAsync((r, e) -> {
            if (e != null) {
                log.error("受理订单编号[{}] >> 生成申请书调用推送电子保函申请单异常：{}", acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo(), e.getMessage(), e);
            }
        });
    }


    /**
     * 解析 受理的清单信息
     */
    private AcceptOrderBO parseApplyGuaranteeInfo(CenterTradeContext<LstApplyReqDTO, XMBaseRespDTO> context) {
        LstApplyReqDTO req = context.getReq();
        long centerId = context.getCenterId();
        long orgId = context.getOrgId();
        //固定得兴担保直开式
        InstitutionOrgCodeEnum institutionOrgCodeEnum = InstitutionOrgCodeEnum.resolve(context.getOrgCode());
//        InstitutionCode curInstitutionCode = InstitutionCode.deXing;
        GuaranteeInstitutionDO institutionDO = getInstitutionIdByCode(institutionOrgCodeEnum);
        String acceptOrderNo = IdGenerate.genAcceptOrderNo(context.getCenterNoEnum());

        ProjectInfoDO projectInfoDO = this.buildProjectInfo(context.getCenterNoEnum(),req, centerId, orgId);
        BidCustomerDO bidCustomerDO = this.buildBidCustomerInfo(req, centerId, orgId);
        UserDO userDO = this.buildUserInfo(req, centerId, orgId);
        AcceptOrderInfoDO acceptOrderInfoDO = this.buildAcceptOrderInfo(acceptOrderNo, req, centerId, orgId, institutionDO);
        InvoiceInfoDO invoiceInfoDO = this.buildInvoiceInfo(req, centerId, orgId);
        invoiceInfoDO.setAcceptOrderNos(acceptOrderNo);

        //计算保费
        CertifyCodeEnum certifyCode = CertifyCodeEnum.resolve(acceptOrderInfoDO.getCertifyCode());
        if (certifyCode.equals(CertifyCodeEnum.HYMMZ)) {
            acceptOrderInfoDO.setGuaranteeFee(getYouXiMZGuaranteeFee(projectInfoDO.getBidBond()));
        } else {
            String feeRate = this.getCurCenterInfo(context).getFeeRate();
            acceptOrderInfoDO.setFeeRate(feeRate);
            Long minFeeYuan = this.getCurCenterInfo(context).getMinFeeYuan();
            Long maxFeeYuan = this.getCurCenterInfo(context).getMaxFeeYuan();
            acceptOrderInfoDO.setGuaranteeFee(this.calcGuaranteeFee(projectInfoDO.getBidBond(), feeRate, minFeeYuan,maxFeeYuan));
        }
        AcceptOrderBO orderBO = AcceptOrderBO.builder().centerId(centerId).orgId(orgId)
                .acceptOrderInfo(acceptOrderInfoDO).projectInfo(projectInfoDO).bidCustomer(bidCustomerDO).userDO(userDO)
                .invoiceInfoDO(invoiceInfoDO).build();

        //默认投标保函类别;
        orderBO.setGuaranteeCategory(GuaranteeCategory.BID);
        //默认担保公司担保类型;
        orderBO.setGuaranteeType(GuaranteeType.GUARANTEE);

        orderBO.setInstitutionOrgCodeEnum(institutionOrgCodeEnum);
        orderBO.setIsInnerApply(false);

        //出函机构赋值
        acceptOrderInfoDO.setInstitutionId(institutionDO.getId());
        acceptOrderInfoDO.setGuaranteeType(orderBO.getGuaranteeType().getTypeStr());
        acceptOrderInfoDO.setGuaranteeCategory(orderBO.getGuaranteeCategory().getCategoryStr());


        return orderBO;
    }


    private AcceptOrderInfoDO buildAcceptOrderInfo(String acceptOrderNo, LstApplyReqDTO req, long centerId, long orgId, GuaranteeInstitutionDO institutionDO) {
        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
        TbMainLiab mainLiab = data.getTbMainLiab();
        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
        String projectCode = mainLiab.getInsureArea();
        String projectName = mainLiab.getBusinessDetail();

        return AcceptOrderInfoDO.builder()
                .centerId(centerId).orgId(orgId)
                .guaranteeNo(IdGenerate.genGuaranteeNo(institutionDO.getInstitutionCode()))
                .centerOrderId(data.getBusinessNo())
                .centerApplyId(data.getApplyId())
                .centerOrderTime(DateUtil.getDatetime())
                .acceptOrderNo(acceptOrderNo)
                .projectName(projectName)
                .sectionName(provinceSupply.getSectionName())
                .bidCustomerName(insuranceSchema.getHolderName())
                //当前投标期限保证金截止时间
                .bidIndate(DateUtil.parseDate(mainLiab.getLiabreportstartdate(), "yyyy-MM-dd HH:mm:ss"))
                .guaranteeType(GuaranteeType.GUARANTEE.getTypeStr())//'保函类型'
                .guaranteeCategory(GuaranteeCategory.BID.getCategoryStr()) //'保函品种'
//                .templateId(null)//'报价模板主键id'
//                .feeRate(null)
//                .guaranteeFee(null)//'保费金额分'
                .status(AcceptOrderStatus.WAIT_SUBMIT_FIRST_TRAIL.getStatus())
//                .guaranteeTime(null)
//                .projectId(null)//  '投保项目主键id' 关联保存时统一设置
//                .bidCustomerId(null)// '投保客户主键id'
//                .institutionId(null) //'开函机构主键'
//                .attachmentId(null)//
//                .applyOrderNo(null)
//                .invoiceFlag(null)
//                .invoiceId(null)
                .warnFlag(0)
//                .warnContent(null)
                .uploadKey(insuranceSchema.getSecretKey())
                .gmtCreate(Date.from(Instant.now()))
                .certifyCode(insuranceSchema.getCertifyCode())
                .build();
    }

    private BidCustomerDO buildBidCustomerInfo(LstApplyReqDTO req, long centerId, long orgId) {
        // 其他信息通过 企业认证补充页面收集
        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
        TbMainLiab mainLiab = data.getTbMainLiab();
        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();

        BidCustomerDO bidCustomer = new BidCustomerDO();
        bidCustomer.setCenterId(centerId);
        bidCustomer.setOrgId(orgId);
        bidCustomer.setBidderName(insuranceSchema.getHolderName());
        bidCustomer.setBidderCreditCode(insuranceSchema.getHolderIdNo());
        bidCustomer.setBidderContactName(insuranceSchema.getFrameNo());
        bidCustomer.setBidderContactTel(insuranceSchema.getHolderMobile());
        bidCustomer.setBidderContactIdcard(insuranceSchema.getBidderContactIdCard());
        bidCustomer.setBidderContactIdcardType(IDType.ID_CARD.getType());
        bidCustomer.setBidderEamil(insuranceSchema.getBidderEmail());
        bidCustomer.setBidderAddress(insuranceSchema.getHolderAddress());
        bidCustomer.setBidderRegAddress(insuranceSchema.getHolderAddress());
        bidCustomer.setLegalPersonName(insuranceSchema.getLegalPersonName());
        bidCustomer.setLegalPersonIdcard(insuranceSchema.getLegalPersonIdcard());
        bidCustomer.setLegalPersonIdcardType(IDType.ID_CARD.getType());
        bidCustomer.setLegalPersonTel(insuranceSchema.getLegalPersonTel());
        bidCustomer.setEnableAutoApprove(0);
        bidCustomer.setBlacklistFlag(0);
//        bidCustomer.setBidderCapital(null);
        bidCustomer.setBidderLegal(insuranceSchema.getLegalPersonName());
//        bidCustomer.setBidderBeginDate(null);
//        bidCustomer.setBidderEndDate(null);
//        bidCustomer.setBidderWebsite(null);
//        bidCustomer.setBidderIpcNo(null);
//        bidCustomer.setLegalBeginDate(null);
//        bidCustomer.setLegalEndDate(null);
        bidCustomer.setLicenseName(insuranceSchema.getBidderAccountName());
//        bidCustomer.setLicenseAccount(insuranceSchema.getBidderAccountNo());
        bidCustomer.setLicenseLegal(insuranceSchema.getLegalPersonName());
        bidCustomer.setLicenseBank(insuranceSchema.getBidderOpenBank());
//        bidCustomer.setLicenseCheckNo(null);
//        bidCustomer.setLicenseNo(null);
        bidCustomer.setStatus(BidCustomerStatus.NORMAL.getStatus());
//        bidCustomer.setAuditDesc(null);
        bidCustomer.setFollowId(insuranceSchema.getFollowId());
//        bidCustomer.setBeiandiquCode(null);
//        bidCustomer.setBankName(insuranceSchema.getBidderOpenBank());
//        bidCustomer.setBankCardNum(insuranceSchema.getBidderAccountNo());
        bidCustomer.setBankUserName(insuranceSchema.getBidderAccountName());
        bidCustomer.setComTelArea(insuranceSchema.getHolderAddress());
        bidCustomer.setComTelNum(insuranceSchema.getHolderMobile());
//        bidCustomer.setProvince(null);
//        bidCustomer.setCity(null);
//        bidCustomer.setDistrict(null);
//        bidCustomer.setEnterpriseId(null);
//        bidCustomer.setResultQueryTimes(null);

        return bidCustomer;

    }

    private UserDO buildUserInfo(LstApplyReqDTO req, long centerId, long orgId) {
        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
        TbMainLiab mainLiab = data.getTbMainLiab();
        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
        return UserDO.builder()
                .umLogin("0")
                .followId(insuranceSchema.getHolderIdNo())
                .username(insuranceSchema.getHolderIdNo())
                .mobileNo(insuranceSchema.getHolderMobile())//改成统一社会信用代码登录
                .name(insuranceSchema.getHolderName())
                .type(UserType.BIDDER.getType())
                .status(UserStatusEnum.NORMAL.name())
                .orgCode("-1")
                .gmtCreate(new Date())
                .gmtModified(new Date())
                .build();
    }

    private ProjectInfoDO buildProjectInfo(CenterNoEnum centerNoEnum,LstApplyReqDTO req, long centerId, long orgId) {
        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
        TbMainLiab mainLiab = data.getTbMainLiab();
        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
        XMTenderer xmTenderer = data.getXmTenderer();

        String projectCode = mainLiab.getInsureArea();
        String projectName = mainLiab.getBusinessDetail();

        return ProjectInfoDO.builder()
                .centerId(centerId).orgId(orgId)
                .projectCode(projectCode).projectName(projectName)
                .sectionCode(provinceSupply.getSectionCode()).sectionName(provinceSupply.getSectionName())
                .contractReckonPrice(yuan2fenLong(mainLiab.getPreTurnOver()))
                .tenderer(xmTenderer.getTenderer())
                .tendererAddress(xmTenderer.getTendererContactAddress())
                .tendererCreditCode(xmTenderer.getTendererCreditCode())
                .tendererBankOpenbank(xmTenderer.getTendererBankOpenbank())
                .tendererBankCode(xmTenderer.getTendererBankCode())
                .tendererBankAccount(xmTenderer.getTendererBankAccount())
                .tendererContact(xmTenderer.getTendererContact())
                .tendererContactTel(xmTenderer.getTendererContactTel())
                .projectAddress(provinceSupply.getProjectAddress())
                .projectDays(provinceSupply.getProjectDays())
                .inviteType(provinceSupply.getInviteType())
                .cityCode(provinceSupply.getCityCode())
                .tenderProjectType(provinceSupply.getTenderProjectType())
                .bidOpenTime(DateUtil.parseDate(mainLiab.getLiabreportstartdate(), "yyyy-MM-dd HH:mm:ss"))//'开标时间'=投标截止日期
                .validPeriod(Integer.valueOf(provinceSupply.getValidPeriod()))//投标有效期（单位：天）
                .bidBond(yuan2fenLong(insuranceSchema.getAmount()))
                .tenderNoticeUrl(provinceSupply.getTenderNoticeUrl())
                .tenderFileUrl(mainLiab.getTenderFileUrl())
                .tenderFileMd5(mainLiab.getTenderFileMD5())//'招标方文件md5校验值'
                .noticePubDate(StringUtils.isNotBlank(mainLiab.getNoticePubDate()) ? DateUtil.parseDate(mainLiab.getNoticePubDate(), "yyyy-MM-dd HH:mm:ss") : null)
                .templateId(AutoDiscernTemplateUtil.getTemplateIdByTenderProjectType(centerNoEnum,provinceSupply.getTenderProjectType()))
//                .remark(null)//无
                .warnFlag(0)// '预警标识0正常 1出函机构无法受理该项目',
                .sourceFlag(0)// '信息来源0自动 1手动',
                .gmtCreate(Date.from(Instant.now()))
                .build();
    }

    private InvoiceInfoDO buildInvoiceInfo(LstApplyReqDTO req, long centerId, long orgId) {
        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
//        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
//        TbMainLiab mainLiab = data.getTbMainLiab();
//        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
        InvoiceInfoVo invoiceInfoVo = data.getInvoiceInfoVo();
        invoiceInfoVo.setCenterId(centerId);
        invoiceInfoVo.setOrgId(orgId);
        InvoiceInfoDO invoiceInfoDO = InvoiceInfoDO.of(invoiceInfoVo);
//        invoiceInfoDO.setId(IdGenerate.getId());
        return invoiceInfoDO;
    }

    private String genTenderFileMd5(String sectionCode,String sectionName, Long centerId, Long orgId, String tenderFileUrl) {
        String tenderFileMd5 = null;
        try {
            if (!StringUtils.isEmpty(tenderFileUrl)) {
                ProjectInfoDO projectInfo = projectInfoService.getBySectionCode(sectionCode,sectionName, centerId, orgId);
                if (projectInfo == null || StringUtils.isEmpty(projectInfo.getTenderFileMd5())) {
                    //download file
                    Path tmpPath = elgResourceService.downloadByURL(tenderFileUrl);

                    String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", "tenderFile", "标段" + sectionCode + "招标文件");
                    Path savePath = elgResourceService.getAbsolutePath(relativePath);
                    tenderFileMd5 = elgResourceService.getFileMD5AsHex(savePath);
                    try {
                        Files.deleteIfExists(tmpPath);
                    } catch (IOException e) {
                        log.error("删除临时招标文件异常：{}", e.getMessage(), e);
                    }
                } else {
                    tenderFileMd5 = projectInfo.getTenderFileMd5();
                }
            }
        } catch (Exception e) {
            log.error("下载招标文件失败：{}", e.getMessage(), e);
        }
        return tenderFileMd5;
    }

    private Long getYouXiMZGuaranteeFee(Long projectAmount) {
        if (projectAmount < 2000000L) {
            return 10000L;
        } else if (projectAmount < 4000000L) {
            return 15000L;
        } else if (projectAmount < 14000000L) {
            return 20000L;
        } else {
            return Math.round(projectAmount * 0.0015);
        }
    }


    /**
     * 将厦门的‘申请数据’转换为目前系统的数据结构
     *
     * @param reqParams 厦门的请求数据
     * @return
     */
    @Override
    protected Map<String, Object> reorganizeParams(Map<String, Object> reqParams) {

        String jsonString = JSONObject.toJSONString(reqParams);
        String clearString = jsonString.replace("\\\"", "\"")
                .replace("\\\\\"", "\"")
                .replace("\"[", "[")
                .replace("]\"", "]")
                .replace("\"{", "{")
                .replace("}\"", "}");


        reqParams = JSONObject.parseObject(clearString, Map.class);

        // 应用ID
        Object appid = reqParams.get("APPID");

        // 申请ID
        Object applyId = reqParams.get("APPLY_ID");

        // 密钥
        String secretKey = (String) reqParams.get("SECRET_KEY");

        //todo:alan 中心回复测试环境暂不需要解密
        String decrypt = secretKey;
        // 解密数据
//        String decrypt = hyMakeInfoConfig.getAuthConfig(CenterNoEnum.XIAMEN).getHyMakeEncryption().decrypt(secretKey);

        // 担保人统一社会信用代码
        Object guarantorCreditCode = reqParams.get("GUARANTOR_CREDIT_CODE");
        // 担保人名称
        Object guarantorName = reqParams.get("GUARANTOR_NAME");
        // 时间戳
        Object timestamp = reqParams.get("TIMESTAMP");
        // 签名值
        Object signature = reqParams.get("SIGNATURE");


        // 申请信息 json
        JSONObject applyInfo = (JSONObject) reqParams.get("APPLY_INFO");

        // 招标申请信息 json
        JSONObject tenderInfo = (JSONObject) reqParams.get("TENDER_INFO");


        // 投标人信息 json
        JSONObject bidder = (JSONObject) reqParams.get("BIDDER");

        // 发票信息 json
        JSONObject invoice = (JSONObject) reqParams.get("INVOICE");


//        String businessNo = applyId.toString();

        TbInsuranceSchema tbInsuranceSchema = new TbInsuranceSchema();
//        tbInsuranceSchema.setAgentCode((String)reqParams.get(""));
//        tbInsuranceSchema.setCertifyCode((String)reqParams.get(""));


        // 由出函机构提供 用于区分不同交易中心的费率、用章、保函格式等 在：CertifyCodeEnum
        tbInsuranceSchema.setCertifyCode("XM001");

//        tbInsuranceSchema.setGuaranteeType((String)reqParams.get(""));
        tbInsuranceSchema.setGuaranteeType("1");

        String bidOpenTime = tenderInfo.getString("BID_OPEN_TIME");
//        String insurStartDate = DateUtil.formateDate(DateUtil.parseDate(bidOpenTime, DateUtil.FORMAT_DATETIME), DateUtil.FORMAT_DATETIME);
        String insurStartDate = bidOpenTime;
        // 当前时间
        tbInsuranceSchema.setInsurDate(DateUtil.getCurrentDate(DateUtil.FORMAT_DATETIME));
        tbInsuranceSchema.setInsurStartDate(insurStartDate);
        tbInsuranceSchema.setInsurEndDate(DateUtil.formateDate(DateUtil.getDayAfter(28), DateUtil.FORMAT_DATETIME));


//        tbInsuranceSchema.setPremium((String)reqParams.get(""));
//        tbInsuranceSchema.setPremium("603");

//        tbInsuranceSchema.setAmount((String)reqParams.get(""));
        tbInsuranceSchema.setAmount(tenderInfo.getString("BID_BOND"));


        tbInsuranceSchema.setHolderName((String) bidder.get("BIDDER_NAME"));
        tbInsuranceSchema.setHolderidType("08");

        tbInsuranceSchema.setHolderIdNo((String) bidder.get("BIDDER_CREDIT_CODE"));
        tbInsuranceSchema.setHolderMobile((String) bidder.get("BIDDER_CONTACT_TEL"));
        tbInsuranceSchema.setHolderAddress((String) bidder.get("BIDDER_ADDRESS"));


        tbInsuranceSchema.setFrameNo((String) bidder.get("BIDDER_CONTACT_NAME"));
        tbInsuranceSchema.setBidderContactIdCard((String) bidder.get("BIDDER_CONTACT_IDCARD"));
        tbInsuranceSchema.setBidderEmail((String) bidder.get("BIDDER_EAMIL"));


        tbInsuranceSchema.setLegalPersonName((String) bidder.get("LEGAL_PERSON_NAME"));
        tbInsuranceSchema.setLegalPersonIdcard((String) bidder.get("LEGAL_PERSON_IDCARD"));
        tbInsuranceSchema.setLegalPersonTel((String) bidder.get("LEGAL_PERSON_TEL"));

        // 获取发票信息中的银行信息，不确定是否为投保人银行信息
        tbInsuranceSchema.setBidderOpenBank((String) invoice.get("BANK_OPENBANK"));
        tbInsuranceSchema.setBidderAccountName((String) invoice.get("COMPANY_NAME"));
        tbInsuranceSchema.setBidderAccountNo((String) invoice.get("BANK_CODE"));


        tbInsuranceSchema.setInsuredName((String) bidder.get("BIDDER_NAME"));
        tbInsuranceSchema.setInsuredIdNo((String) bidder.get("BIDDER_CREDIT_CODE"));
        tbInsuranceSchema.setInsuredidType("08");
        tbInsuranceSchema.setInsuredmobile((String) bidder.get("BIDDER_CONTACT_TEL"));
        tbInsuranceSchema.setInsuredAddress((String) bidder.get("BIDDER_ADDRESS"));
        tbInsuranceSchema.setInsuredgrantCountry((String) bidder.get("BIDDER_CONTACT_NAME"));

        tbInsuranceSchema.setInsuredBankCode((String) invoice.get("BANK_CODE"));
        tbInsuranceSchema.setInsuredBankOpenBank((String) invoice.get("BANK_OPENBANK"));
        tbInsuranceSchema.setInsuredBankAccount((String) invoice.get("COMPANY_NAME"));


        tbInsuranceSchema.setInputDate(String.valueOf(applyInfo.get("CREATE_TIME")));

//        tbInsuranceSchema.setSpecialAgreement((String)reqParams.get(""));
        tbInsuranceSchema.setGuarantorName((String) guarantorName);
//        tbInsuranceSchema.setGuarantorIdType((String)reqParams.get(""));
//        tbInsuranceSchema.setGuarantorIdNo((String)reqParams.get(""));
        tbInsuranceSchema.setGuarantorIdCode((String) guarantorCreditCode);


//        tbInsuranceSchema.setPreferentialWay((String)reqParams.get(""));
//        tbInsuranceSchema.setPreferentialValue((String)reqParams.get(""));
        tbInsuranceSchema.setFollowId((String) appid);
        tbInsuranceSchema.setSecretKey(decrypt);


        TbMainLiab tbMainLiab = new TbMainLiab();
        tbMainLiab.setBusinessDetail((String) tenderInfo.get("TENDER_PROJECT_NAME"));
        tbMainLiab.setBusinessSite((String) tenderInfo.get("PROJECT_ADDRESS"));
        tbMainLiab.setCertificateDepart((String) tenderInfo.get("PROJECT_DAYS"));
        tbMainLiab.setInsureArea((String) tenderInfo.get("TENDER_PROJECT_CODE"));

//        String bidOpenTime = (String) tenderInfo.get("BID_OPEN_TIME");
//        Date bidOpenDate = DateUtil.parseDate(bidOpenTime, "yyyyMMdd HH:mm:ss");
//        DateUtil.parseDate(mainLiab.getLiabreportstartdate(), "yyyy-MM-dd HH:mm:ss")


//        LocalDateTime dateTime = LocalDateTime.parse(bidOpenTime, DateTimeFormatter.ofPattern(DateUtil.FORMAT_DATETIME));
//        String formattedTime = dateTime.format(DateTimeFormatter.ofPattern(DateUtil.FORMAT_DATETIME));
        tbMainLiab.setLiabreportstartdate(bidOpenTime);

        tbMainLiab.setPreTurnOver((String) tenderInfo.get("CONTRACT_RECKON_PRICE"));
        tbMainLiab.setTenderFileUrl((String) tenderInfo.get("TENDER_FILE_URL"));
        tbMainLiab.setTenderFileMD5((String) tenderInfo.get("TENDER_FILE_MD5"));
//        tbMainLiab.setEvabidMethod((String) tenderInfo.get(""));

        String tenderNoticeIssueTime = (String) tenderInfo.get("TENDER_NOTICE_ISSUE_TIME");

//        LocalDate tenderDate = LocalDate.parse(tenderNoticeIssueTime, DateTimeFormatter.ofPattern("yyyyMMdd"));
//        LocalDateTime tenderDateTime = tenderDate.atStartOfDay(); // 将日期转换为当天 00:00:00 的日期时间
//        String tenderFormattedTime = tenderDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        tbMainLiab.setNoticePubDate(tenderNoticeIssueTime);


        List<TbSection> tbSection = new ArrayList<>();

        TbSection tbSection1 = new TbSection();
        tbSection1.setSectionName((String) tenderInfo.get("SECTION_NAME"));
        tbSection1.setSectionCode((String) tenderInfo.get("SECTION_CODE"));
        tbSection1.setBidBonds((String) tenderInfo.get("BID_BOND"));
        tbSection.add(tbSection1);


        TbProvinceSupply tbProvinceSupply = new TbProvinceSupply();
//        tbProvinceSupply.setTradeCenter((String) tenderInfo.get("不能为空，不知道是啥"));
        tbProvinceSupply.setTradeCenter(CenterNoEnum.XIAMEN.getCenterNo());
        tbProvinceSupply.setApprovalNo((String) tenderInfo.get("APPROVAL_CODE"));
        tbProvinceSupply.setInvestProjectCode((String) tenderInfo.get("INVEST_PROJECT_CODE"));

        tbProvinceSupply.setTenderProjectCode((String) tenderInfo.get("TENDER_PROJECT_CODE"));
        tbProvinceSupply.setTenderProjectName((String) tenderInfo.get("TENDER_PROJECT_NAME"));

        tbProvinceSupply.setSectionCode((String) tenderInfo.get("SECTION_CODE"));
        tbProvinceSupply.setSectionName((String) tenderInfo.get("SECTION_NAME"));
        tbProvinceSupply.setCityCode((String) tenderInfo.get("TOWN_CODE"));
        tbProvinceSupply.setTenderProjectType((String) tenderInfo.get("TENDER_PROJECT_TYPE"));
        tbProvinceSupply.setInviteType(String.valueOf(tenderInfo.get("INVITE_TYPE")));
        tbProvinceSupply.setProjectAddress(String.valueOf(tenderInfo.get("PROJECT_ADDRESS")));
        tbProvinceSupply.setProjectDays(String.valueOf(tenderInfo.get("PROJECT_DAYS")));
        tbProvinceSupply.setValidPeriod((String) tenderInfo.get("VALID_PERIOD"));
        tbProvinceSupply.setTenderNoticeUrl((String) tenderInfo.get("TENDER_NOTICE_URL"));


        InvoiceInfoVo invoiceInfoVo = new InvoiceInfoVo();
//        invoiceInfoVo.setId(IdGenerate.getId());
//        invoiceInfoVo.setAcceptOrderNos(vo.getAcceptOrderNo());
//        invoiceInfoVo.setCenterId(acceptOrderInfoDO.getCenterId());
//        invoiceInfoVo.setOrgId(acceptOrderInfoDO.getOrgId());
//        invoiceInfoVo.setInvoiceTitle(bidCustomerDO.getBidderName());
        //开票类型蓝票
        invoiceInfoVo.setInvoiceType(1);
        invoiceInfoVo.setInvoiceLine(String.valueOf(0).equals(invoice.getString("INVOICE_TYPE"))
                ? InvoiceLineEnum.PC.getInvoiceLineCode() : InvoiceLineEnum.BS.getInvoiceLineCode());
//        invoiceInfoDO.setInvoiceNo();
        invoiceInfoVo.setCustomerName(invoice.getString("COMPANY_NAME"));
        invoiceInfoVo.setCustomerCreditCode(invoice.getString("BIDDER_CODE"));
        invoiceInfoVo.setCustomerBankCode(invoice.getString("BANK_CODE"));
        invoiceInfoVo.setCustomerOpneBank(invoice.getString("BANK_OPENBANK"));
        invoiceInfoVo.setCustomerAddress(invoice.getString("COMPANY_ADDRESS"));
        invoiceInfoVo.setCustomerPhone(invoice.getString("COMPANY_TEL"));
        //发票购买方电话若有开票座机号则取该值，其他默认取客户经办人联系电话
//        String customerPhone = StringUtils.isNotBlank(bidCustomerDO.getComTelNum()) ? bidCustomerDO.getComTelNum() : bidCustomerDO.getBidderContactTel();
//        invoiceInfoVo.setCustomerPhone(customerPhone);

        invoiceInfoVo.setCustomerContactName(invoice.getString("RECEIVE_NAME"));
        invoiceInfoVo.setCustomerContactTel(invoice.getString("RECEIVE_TEL"));

        //客户邮箱错误 会导致开票失败
//        invoiceInfoDO.setCustomerContactEamil(invoice.getString("COMPANY_EMAIL"));
        invoiceInfoVo.setCustomerContactAddress(invoice.getString("RECEIVE_ADDRESS"));
        invoiceInfoVo.setStatus(InvoiceStatusEnum.APPLY.getValue());
//        invoiceInfoVo.setAmount(acceptOrderInfoDO.getGuaranteeFee());
//        invoiceInfoVo.setAmountOfChinaese(CurrencyUpperUtil.fenToCurrencyUpper(acceptOrderInfoDO.getGuaranteeFee()));
//        invoiceInfoVo.setSellerName(sellerInfoDO.getSellerName());
//        invoiceInfoVo.setSellerCreditCode(sellerInfoDO.getSellerCreditCode());
//        invoiceInfoVo.setSellerBankCode(sellerInfoDO.getSellerBankCode());
//        invoiceInfoVo.setSellerOpenBank(sellerInfoDO.getSellerOpenBank());
//        invoiceInfoVo.setSellerAddress(sellerInfoDO.getSellerAddress());
//        invoiceInfoVo.setSellerPhone(sellerInfoDO.getSellerPhone());
//        invoiceInfoVo.setHandler(sellerInfoDO.getHandler());
//        invoiceInfoVo.setInvoiceRemark("电子保函");
//        invoiceInfoVo.setOrderCount(1);
//        invoiceInfoVo.setGmtCreate(new Date());
//        invoiceInfoVo.set

        XMTenderer xmTenderer = new XMTenderer();
        xmTenderer.setTenderer(String.valueOf(tenderInfo.get("TENDERER")));
        xmTenderer.setTendererCreditCode(String.valueOf(tenderInfo.get("TENDERER_CREDIT_CODE")));
        xmTenderer.setTendererBankCode(String.valueOf(tenderInfo.get("TENDERER_BANK_CODE")));
        xmTenderer.setTendererBankOpenbank(String.valueOf(tenderInfo.get("TENDERER_BANK_OPENBANK")));
        xmTenderer.setTendererBankAccount(String.valueOf(tenderInfo.get("TENDERER_BANK_ACCOUNT")));
        xmTenderer.setTendererContact(String.valueOf(tenderInfo.get("TENDERER_CONTACT")));
        xmTenderer.setTendererContactTel(String.valueOf(tenderInfo.get("TENDERER_CONTACT_TEL")));
        xmTenderer.setTendererContactAddress(String.valueOf(tenderInfo.get("TENDERER_CONTACT_ADDRESS")));

        TbPolicyDto tbPolicyDto = new TbPolicyDto();
        // 厦门新增申请标识ID存储
        tbPolicyDto.setApplyId(String.valueOf(applyId));
        // 该字段存储为，center_order_id
        tbPolicyDto.setBusinessNo(String.valueOf(applyInfo.get("ORDER_NO")));
        tbPolicyDto.setTbInsuranceSchema(tbInsuranceSchema);
        tbPolicyDto.setTbMainLiab(tbMainLiab);
        tbPolicyDto.setTbSection(tbSection);
        tbPolicyDto.setTbProvinceSupply(tbProvinceSupply);
        tbPolicyDto.setInvoiceInfoVo(invoiceInfoVo);
        tbPolicyDto.setXmTenderer(xmTenderer);


        List<TbPolicyDto> tbPolicyDtoList = new ArrayList<>();
        tbPolicyDtoList.add(tbPolicyDto);

        Map<String, Object> params = new HashMap<>();

        JSONArray jsonArray = JSONObject.parseArray(JSONObject.toJSONString(tbPolicyDtoList));


        params.put("tbPolicyDtoList", jsonArray);

        return params;
    }

    /**
     * 更新申请信息及重新出函
     *
     * @param acceptOrderBO
     * @return
     */
    private XMBaseRespDTO updateLstApply(AcceptOrderBO acceptOrderBO) {
        XMBaseRespDTO resp = XMBaseRespDTO.builder()
                .success(false)
                .errorCode(XMRespCodeEnum.FAILURE.getRespCode())
                .errorDesc("项目修改失败，请联系客服处理")
                .build();
        final AcceptOrderInfoDO dbOrderInfo = acceptOrderInfoService.selectOne(AcceptOrderInfoDOCondition.builder()
                .andCenterIdEq(acceptOrderBO.getAcceptOrderInfo().getCenterId())
                .andCenterOrderIdEq(acceptOrderBO.getAcceptOrderInfo().getCenterOrderId()).build());

        if (dbOrderInfo.getStatus() == AcceptOrderStatus.FINISH.getStatus()) {
            resp.setErrorDesc("保函已完成，不能进行修改");
            return resp;
        }

        if (dbOrderInfo.getStatus() == AcceptOrderStatus.CANCEL.getStatus()) {
            resp.setErrorDesc("保函已取消，不能进行修改");
            return resp;
        }

        if (dbOrderInfo.getStatus() == AcceptOrderStatus.REVOKE_PROCESSING.getStatus()) {
            resp.setErrorDesc("退保审核中，不能进行修改");
            return resp;
        }

        if (dbOrderInfo.getStatus() == AcceptOrderStatus.REVOKE_SUCCESS.getStatus()) {
            resp.setErrorDesc("退保成功，不能进行修改");
            return resp;
        }

        AcceptOrderInfoDO updateOrderInfo = new AcceptOrderInfoDO();
        BeanUtil.copyProperties(dbOrderInfo, updateOrderInfo);
        final CopyOptions copyOption = CopyOptions.create(null, true);
        BeanUtil.copyProperties(acceptOrderBO.getAcceptOrderInfo(), updateOrderInfo, copyOption);
        updateOrderInfo.setAcceptOrderNo(dbOrderInfo.getAcceptOrderNo());
        acceptOrderBO.setAcceptOrderInfo(updateOrderInfo);

        ProjectInfoDO dbProjectInfo = projectInfoService.selectById(dbOrderInfo.getProjectId());
        if (!acceptOrderBO.getProjectInfo().getBidBond().equals(dbProjectInfo.getBidBond())) {
            resp.setErrorDesc("项目保证金金额发生变化，请退保后重新申请保函");
            return resp;
        }
        BeanUtil.copyProperties(acceptOrderBO.getProjectInfo(), dbProjectInfo, copyOption);
        acceptOrderBO.setProjectInfo(dbProjectInfo);


        BidCustomerDO dbBidCustomerInfo = bidCustomerService.selectById(dbOrderInfo.getBidCustomerId());
        if (!acceptOrderBO.getBidCustomer().getBidderCreditCode().equals(dbBidCustomerInfo.getBidderCreditCode())) {
            resp.setErrorDesc("投保企业统一社会信用代码发生变化，请退保后重新申请保函");
            return resp;
        }
        BeanUtil.copyProperties(acceptOrderBO.getBidCustomer(), dbBidCustomerInfo, copyOption);
        acceptOrderBO.setBidCustomer(dbBidCustomerInfo);

        UserDO dbUserInfo = userServiceImpl.selectOne(UserDOCondition.builder()
                .andUsernameEq(dbBidCustomerInfo.getBidderCreditCode()).andTypeEq(UserType.BIDDER.getType())
                .build());
        BeanUtil.copyProperties(acceptOrderBO.getUserDO(), dbUserInfo, copyOption);
        acceptOrderBO.setUserDO(dbUserInfo);

        acceptOrderBO = acceptOrderInfoService.saveAcceptOrderBO(acceptOrderBO);

        makeAndSaveApplyFile(acceptOrderBO);

        resp = XMBaseRespDTO.builder()
                .success(true)
                .errorCode(XMRespCodeEnum.SUCCESS.getRespCode())
                .errorDesc("项目修改成功")
                .build();
        return resp;

    }
}

